#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
脑电数据结果容器类

统一各个过滤器的输入输出格式，类似于Web服务的标准Response类
所有过滤器都接收和返回这个标准格式的数据容器
"""

import time
from typing import Dict, Any, Optional


class BrainWaveResult:
    """
    脑电数据结果容器类
    
    标准化数据格式（8频域支持）：
    - rawValue: 原始脑电信号值
    - delta: Delta波段值 (0.5-4Hz)
    - theta: Theta波段值 (4-8Hz)
    - low_alpha: Low Alpha波段值 (8-13Hz)
    - high_alpha: High Alpha波段值 (8-13Hz)
    - low_beta: Low Beta波段值 (13-30Hz)
    - high_beta: High Beta波段值 (13-30Hz)
    - low_gamma: Low Gamma波段值 (30-100Hz)
    - mid_gamma: Mid Gamma波段值 (30-100Hz)
    
    向后兼容属性：
    - alpha: Alpha波段值 (low_alpha + high_alpha)
    - beta: Beta波段值 (low_beta + high_beta)
    - gamma: Gamma波段值 (low_gamma + mid_gamma)
    
    新增分析指标：
    - alpha_asymmetry: Alpha不对称性 (high_alpha / low_alpha)
    - beta_asymmetry: Beta不对称性 (high_beta / low_beta)
    - gamma_coherence: Gamma一致性 (mid_gamma / low_gamma)
    
    其他属性：
    - poorSignal: 信号质量指标 (0-200)
    - attention: 注意力值 (0-100)
    - meditation: 冥想值 (0-100)
    """
    
    def __init__(self, rawValue: int = 0, delta: int = 0, theta: int = 0, 
                 low_alpha: int = 0, high_alpha: int = 0,
                 low_beta: int = 0, high_beta: int = 0,
                 low_gamma: int = 0, mid_gamma: int = 0,
                 alpha: int = None, beta: int = None, gamma: int = None,
                 poorSignal: int = 200, attention: int = 0, meditation: int = 0):
        """
        初始化脑电数据容器
        
        Args:
            rawValue: 原始脑电信号值
            delta: Delta波段值
            theta: Theta波段值
            low_alpha: Low Alpha波段值
            high_alpha: High Alpha波段值
            low_beta: Low Beta波段值
            high_beta: High Beta波段值
            low_gamma: Low Gamma波段值
            mid_gamma: Mid Gamma波段值
            alpha: Alpha波段值（向后兼容，如果未提供则自动计算）
            beta: Beta波段值（向后兼容，如果未提供则自动计算）
            gamma: Gamma波段值（向后兼容，如果未提供则自动计算）
            poorSignal: 信号质量 (0=最好, 200=最差)
            attention: 注意力值
            meditation: 冥想值
        """
        # 核心脑电数据（8频域）
        self.rawValue = rawValue
        self.delta = delta
        self.theta = theta
        self.low_alpha = low_alpha
        self.high_alpha = high_alpha
        self.low_beta = low_beta
        self.high_beta = high_beta
        self.low_gamma = low_gamma
        self.mid_gamma = mid_gamma
        
        # 向后兼容属性（合成频域）
        self.alpha = alpha if alpha is not None else (low_alpha + high_alpha)
        self.beta = beta if beta is not None else (low_beta + high_beta)
        self.gamma = gamma if gamma is not None else (low_gamma + mid_gamma)
        
        # 信号质量和状态
        self.poorSignal = poorSignal
        self.attention = attention
        self.meditation = meditation
        
        # 新增分析指标
        self.alpha_asymmetry = self._calculate_asymmetry(high_alpha, low_alpha)
        self.beta_asymmetry = self._calculate_asymmetry(high_beta, low_beta)
        self.gamma_coherence = self._calculate_coherence(mid_gamma, low_gamma)
        
        # 元数据
        self.timestamp = time.time()
        self.processing_info = {}  # 存储处理过程信息
        
    def _calculate_asymmetry(self, high_value: int, low_value: int) -> float:
        """计算不对称性指标"""
        if low_value == 0:
            return 0.0
        return high_value / low_value
    
    def _calculate_coherence(self, mid_value: int, low_value: int) -> float:
        """计算一致性指标"""
        if low_value == 0:
            return 0.0
        return mid_value / low_value
    
    def update_analysis_indicators(self):
        """更新分析指标"""
        self.alpha_asymmetry = self._calculate_asymmetry(self.high_alpha, self.low_alpha)
        self.beta_asymmetry = self._calculate_asymmetry(self.high_beta, self.low_beta)
        self.gamma_coherence = self._calculate_coherence(self.mid_gamma, self.low_gamma)
        
        # 更新合成频域
        self.alpha = self.low_alpha + self.high_alpha
        self.beta = self.low_beta + self.high_beta
        self.gamma = self.low_gamma + self.mid_gamma
    
    def to_dict(self) -> Dict[str, Any]:
        """转换为字典格式"""
        return {
            'rawValue': self.rawValue,
            'delta': self.delta,
            'theta': self.theta,
            'low_alpha': self.low_alpha,
            'high_alpha': self.high_alpha,
            'low_beta': self.low_beta,
            'high_beta': self.high_beta,
            'low_gamma': self.low_gamma,
            'mid_gamma': self.mid_gamma,
            'alpha': self.alpha,
            'beta': self.beta,
            'gamma': self.gamma,
            'alpha_asymmetry': self.alpha_asymmetry,
            'beta_asymmetry': self.beta_asymmetry,
            'gamma_coherence': self.gamma_coherence,
            'poorSignal': self.poorSignal,
            'attention': self.attention,
            'meditation': self.meditation,
            'timestamp': self.timestamp,
            'processing_info': self.processing_info
        }
    
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> 'BrainWaveResult':
        """从字典创建实例"""
        result = cls(
            rawValue=data.get('rawValue', 0),
            delta=data.get('delta', 0),
            theta=data.get('theta', 0),
            low_alpha=data.get('low_alpha', 0),
            high_alpha=data.get('high_alpha', 0),
            low_beta=data.get('low_beta', 0),
            high_beta=data.get('high_beta', 0),
            low_gamma=data.get('low_gamma', 0),
            mid_gamma=data.get('mid_gamma', 0),
            alpha=data.get('alpha'),
            beta=data.get('beta'),
            gamma=data.get('gamma'),
            poorSignal=data.get('poorSignal', 200),
            attention=data.get('attention', 0),
            meditation=data.get('meditation', 0)
        )
        
        if 'timestamp' in data:
            result.timestamp = data['timestamp']
        if 'processing_info' in data:
            result.processing_info = data['processing_info']
            
        return result
    
    @classmethod
    def from_neuropy(cls, neuropy_instance) -> 'BrainWaveResult':
        """从NeuroPy实例创建（支持8频域）"""
        return cls(
            rawValue=neuropy_instance.rawValue,
            delta=neuropy_instance.delta,
            theta=neuropy_instance.theta,
            low_alpha=neuropy_instance.lowAlpha,
            high_alpha=neuropy_instance.highAlpha,
            low_beta=neuropy_instance.lowBeta,
            high_beta=neuropy_instance.highBeta,
            low_gamma=neuropy_instance.lowGamma,
            mid_gamma=neuropy_instance.midGamma,
            poorSignal=neuropy_instance.poorSignal,
            attention=neuropy_instance.attention,
            meditation=neuropy_instance.meditation
        )
    
    def copy(self) -> 'BrainWaveResult':
        """创建副本"""
        new_result = BrainWaveResult(
            rawValue=self.rawValue,
            delta=self.delta,
            theta=self.theta,
            low_alpha=self.low_alpha,
            high_alpha=self.high_alpha,
            low_beta=self.low_beta,
            high_beta=self.high_beta,
            low_gamma=self.low_gamma,
            mid_gamma=self.mid_gamma,
            poorSignal=self.poorSignal,
            attention=self.attention,
            meditation=self.meditation
        )
        new_result.timestamp = self.timestamp
        new_result.processing_info = self.processing_info.copy()
        return new_result
    
    def update_band(self, band_name: str, value: int, processing_note: str = None):
        """
        更新指定波段的值
        
        Args:
            band_name: 波段名称 ('delta', 'theta', 'low_alpha', 'high_alpha', 
                      'low_beta', 'high_beta', 'low_gamma', 'mid_gamma',
                      'alpha', 'beta', 'gamma')
            value: 新的波段值
            processing_note: 处理说明
        """
        if hasattr(self, band_name):
            old_value = getattr(self, band_name)
            setattr(self, band_name, value)
            
            # 如果更新的是8频域值，需要更新合成频域和分析指标
            if band_name in ['low_alpha', 'high_alpha', 'low_beta', 'high_beta', 'low_gamma', 'mid_gamma']:
                self.update_analysis_indicators()
            
            # 记录处理信息
            if processing_note:
                if 'band_updates' not in self.processing_info:
                    self.processing_info['band_updates'] = []
                
                self.processing_info['band_updates'].append({
                    'band': band_name,
                    'old_value': old_value,
                    'new_value': value,
                    'note': processing_note,
                    'timestamp': time.time()
                })
    
    def add_processing_step(self, step_name: str, details: Dict[str, Any]):
        """
        添加处理步骤信息
        
        Args:
            step_name: 处理步骤名称
            details: 处理详情
        """
        if 'processing_steps' not in self.processing_info:
            self.processing_info['processing_steps'] = []
        
        self.processing_info['processing_steps'].append({
            'step': step_name,
            'details': details,
            'timestamp': time.time()
        })
    
    def is_good_signal(self) -> bool:
        """判断是否为良好信号"""
        return self.poorSignal < 50
    
    def get_total_power(self) -> int:
        """获取总功率（所有8频域之和）"""
        return (self.delta + self.theta + self.low_alpha + self.high_alpha + 
                self.low_beta + self.high_beta + self.low_gamma + self.mid_gamma)
    
    def get_total_power_legacy(self) -> int:
        """获取总功率（5频域合成，向后兼容）"""
        return self.delta + self.theta + self.alpha + self.beta + self.gamma
    
    def get_band_ratio(self, band_name: str, use_8_bands: bool = True) -> float:
        """
        获取指定波段的功率占比
        
        Args:
            band_name: 波段名称
            use_8_bands: 是否使用8频域计算总功率（默认True）
            
        Returns:
            float: 功率占比 (0.0-1.0)
        """
        total_power = self.get_total_power() if use_8_bands else self.get_total_power_legacy()
        if total_power == 0:
            return 0.0
        
        band_value = getattr(self, band_name, 0)
        return band_value / total_power
    
    def __str__(self) -> str:
        """字符串表示（8频域）"""
        return (f"BrainWaveResult(raw={self.rawValue}, "
                f"δ={self.delta}, θ={self.theta}, "
                f"α_l={self.low_alpha}, α_h={self.high_alpha}, "
                f"β_l={self.low_beta}, β_h={self.high_beta}, "
                f"γ_l={self.low_gamma}, γ_m={self.mid_gamma}, "
                f"poor={self.poorSignal})")
    
    def __repr__(self) -> str:
        """详细字符串表示"""
        return self.__str__()